package com.yichen.ycOJ.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yichen.ycOJ.common.ErrorCode;
import com.yichen.ycOJ.exception.BusinessException;
import com.yichen.ycOJ.judge.codesandbox.CodeSandBox;
import com.yichen.ycOJ.judge.codesandbox.model.ExecutionCodeRequest;
import com.yichen.ycOJ.judge.codesandbox.model.ExecutionCodeResponse;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @Author: yichenwu
 * @Date:2024/3/28 17:18
 */

/**
 * 远程代码沙箱
 */
public class RemoteCodeSandBox implements CodeSandBox {
    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";
    @Override
    public List<ExecutionCodeResponse> executeCode(ExecutionCodeRequest executionCodeRequest) {
        System.out.println("远程代码沙箱.......................................");
        String url = "192.168.241.130:8090/codeSandBox/executeCode";
        String body = JSONUtil.toJsonStr(executionCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(body)
                .execute()
                .body();
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"RemoteCodeSandBox error: " + responseStr);
        }
        List<ExecutionCodeResponse> list = JSONUtil.toList(responseStr, ExecutionCodeResponse.class);
        return list;
    }
}
